// vim:set tabstop=4 shiftwidth=4 softtabstop=4 expandtab foldcolumn=1 foldmethod=marker:
/**
 * Project: LteERP
 * File:    src/filer/LoginFilter.java
 *
 *  Check one user whether had logined in the system.
 *
 *  we add this filter before all Servlet ,
 *  for check one user whether had logined in the system.
 *
 *  @package:   com.m5anet.filter
 *  @author:    Mike.G  (hylinux@gmail.com)
 *  @license:   http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1 
 *  @copyright: http://www.5anet.com
 *
 */
package com.m5anet.filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.io.IOException;

public class LoginFilter implements Filter {

    private FilterConfig config = null;

    public void init(FilterConfig config ) throws ServletException {
           
        this.config = config;
    }
    
    public void destroy() {


    }

    public void doFilter(
            ServletRequest req,
            ServletResponse res,
            FilterChain chain ) throws IOException, ServletException {

        HttpSession session = (( HttpServletRequest)req).getSession();
        //check user whether had login syste.
        //if not ,will forward the login page
        String userName = (String)session.getAttribute("username");

        String requestURI = ( ( HttpServletRequest) req ).getServletPath();

        if ( userName == null && ( requestURI == null || !requestURI.endsWith("Login.do") ) ) {
            ServletContext context = config.getServletContext();
            RequestDispatcher dispatcher = context.getRequestDispatcher("/showlogin.jsp");
            dispatcher.forward(req, res);
            return;
        }

        chain.doFilter(req, res);

    }
}

